package test.nettyrpc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import test.nettyrpc.model.MessageKeyVal;

import java.util.Map;
import java.util.concurrent.*;
import java.util.logging.Level;

public class MessageRecvExecutor implements ApplicationContextAware, InitializingBean {

    private String serverAddress;
    private String serverPort;

    private Map<String, Object> handleMap = new ConcurrentHashMap<>();

    private ExecutorService es = Executors.newFixedThreadPool(10);


    public MessageRecvExecutor(String serverAddress, String serverPort) {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        try {
            MessageKeyVal messageKeyVal = (MessageKeyVal) ctx.getBean("rpcbean");
            Map<String, Object> messageKeyVal1 = messageKeyVal.getMessageKeyVal();
            for (String s : messageKeyVal1.keySet()) {
                handleMap.put(s, messageKeyVal1.get(s));
            }
        } catch (Exception e) {
            java.util.logging.Logger.getLogger(MessageRecvExecutor.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    /**
     * 启动netty服务
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup(2);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new MessageRecvChannelInitializer(handleMap))
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture futrue = serverBootstrap.bind(serverAddress, Integer.valueOf(serverPort)).sync();
            System.out.printf("[author caijing] Netty RPC Server start success ip:%s port:%s\n", serverAddress, serverPort);
            futrue.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
